<?php
// argv[1]: for login
// argv[2]: unset: get the detail links; 
//			download=current-...: download from the certain file
// argv[3]: unset or "null" for downloading complete file,
//			number for downloading from the breakpoint
// argv[4]: unset: donwload next file; self: download itself
// argv[5]: unset: download 500M; download-all: download the whole

// $url is one line in detail_links.txt, not including "\n"
function download_file($url, $argv, $cookie_file)
{
	$ch = curl_init('http://www.javnow.com/'.$url);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_REFERER, 'http://www.javnow.com');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
	curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);   
	$result = curl_exec($ch);
	$error = curl_error($ch);
	if ($error)
		file_put_contents('download.log', $error."\n", FILE_APPEND);
	curl_close($ch);

	// download file
	if (!preg_match('/download\/[^"]+/', $result, $match))
	{
		file_put_contents('download.log', "no download link\n", FILE_APPEND);
	}
	else {
		$film_url = 'http://www.javnow.com/'.$match[0];
		$t = parse_url($film_url);
		$host = $t['host'];
		$file = $t['path'];
		$fp = fsockopen($host, 80, $errno, $errstr, 30);
		if($fp)
		{
			$header = "GET $file HTTP/1.1\r\n";
			$header .= "Host: $host\r\n";
			$header .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; zh-CN; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1\r\n";
			$header .= "Referer: http://$host\r\n";
			$header .= "Connection: Close\r\n";
			// get cookie from cookie_file
			$cookie_str = file($cookie_file);
			$cookie = array();
			foreach ($cookie_str as $c_value)
			{
				$c_value = trim($c_value);
				if (0 === strpos($c_value, 'www.javnow.com'))
				{
					$tmp = explode("\t", $c_value);
					$cookie[] = $tmp[5].'='.$tmp[6];
				}
			}
			$cookie = implode('&', $cookie);
			$header .= "Cookie: ".$cookie."\r\n\r\n";
			fwrite($fp, $header);
			$f_name = 'films/'.str_replace('download/', '', $match[0]);
			$film = fopen($f_name, "ab");
			file_put_contents('download.log', "$f_name\n", FILE_APPEND);
			$i = 1;
			$beginning = false;
			$gt490 = false; // greater than 490M
			// Start buffered download
			while (!feof($fp))
			{
				$s = fgets($fp, 4096);
				if (false !== strpos($s, 'Content-Length:'))
				{
					$size = (int)(trim(str_replace('Content-Length:', '', $s)));
				}
				elseif ('' == trim($s) && !$beginning) 
				{// skip the header, there is a blank line between header and body
					$beginning = true;
				}
				elseif ($beginning)
				{
					if (!isset($argv[3]) || "null" == $argv[3] || (int)($argv[3]) > 0 && $i > (int)($argv[3]))
					{
						fwrite($film, $s);
						if (1 == $i % 10000 || $gt490)
							file_put_contents('download.log', $film_url."---".$i." came in\n", FILE_APPEND);
					}
					$i ++;
				}

				unset($s);
				flush();

				if (!(isset($argv[5]) && 'download-all' == $argv[5]))
				{
					clearstatcache();
					$fs = filesize($f_name);
					if (!$gt490 && $fs > 490000000)
						$gt490 = true;
					elseif ($fs > 500000000)
						break;
				}
			}
			file_put_contents('download.log', $film_url."---".($i - 1).", total: $size\n", FILE_APPEND);
			unset($i);
			unset($film_url);
			unset($argv);
			fclose($film);
			fclose($fp);

			flush();
		}

		echo $errstr;
	}
}

$cookie_file = '1.txt';

// set the first argment as "login" to log in again
if (isset($argv[1]) && 'login' == $argv[1]) 
{
    //$post_fields = 'submit=submit&txtemail=tennis&txtpassword=shuikuen';
	$post_fields = 'submit=submit&txtemail=dranet&txtpassword=ghost96r';
    $ch = curl_init('http://www.javnow.com/midlogin.php');
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_REFERER, 'http://www.javnow.com');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);   
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);   
    $result = curl_exec($ch);
	$error = curl_error($ch);
	if ($error)
		file_put_contents('download.log', $error."\n", FILE_APPEND);
    curl_close($ch);
}

if (!(isset($argv[2]) && false !== strpos($argv[2], 'download')))
{// get the detail list
	$ch = curl_init('http://www.javnow.com/index.php?show=2012-05-01');
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_REFERER, 'http://www.javnow.com');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
	curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);   
	$result = curl_exec($ch);
	file_put_contents('download.log', curl_error($ch)."\n", FILE_APPEND);
	curl_close($ch);

	//file_put_contents('2.txt', $result);

	if (preg_match_all('/details\.php\?[^"]+/', $result, $matches))
	{
		$detail_links = $matches[0];
		foreach($detail_links as $detail_link)
		{
			if (false !== strpos($detail_link, '?f='))
				file_put_contents('detail_links.txt', $detail_link."\n", FILE_APPEND);
		}

		// start download the first file
		$links = file('detail_links.txt');
		$link = trim($links[0]);
		//download_file($link, $argv, $cookie_file);
		exit;
	}
}
else{
	// get download link
	$current_url = str_replace('download=current-', '', $argv[2]);
	if (isset($argv[4]) && 'self' == $argv[4])
	{// if argv[4] is 'self', will download the current file, not the next one.
		$need_download_url = $current_url;
	}
	else
	{
		$links = file('detail_links.txt');
		$current_key = array_search($current_url."\n", $links);
		$need_download_key = $current_key + 1;
		$need_download_url = trim($links[$need_download_key]);
	}
	
	download_file($need_download_url, $argv, $cookie_file);
	exit;
}

?>